<template>
  <div class="editor-container w-full">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="content"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, computed } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import Config from "@/config/env";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const toolbarConfig = {};
const token = Storage.get("token", true);
const editorConfig = computed(() => ({
  placeholder: t("editorWang.请输入内容"),
  MENU_CONF: {
    uploadImage: {
      server: Config.baseUrl + "/api/file/picture",
      fieldName: "file",
      headers: {
        Authorization: "Bearer " + token,
      },
      customInsert(res, insertFn) {
        // res 即服务端的返回结果
        if (res.status === 200) {
          // 插入图片到编辑器
          insertFn(res.data.url, res.data.alt, res.data.href);
        } else {
          console.error("上传图片失败", res);
        }
      },
    },
    uploadVideo: {
      server: Config.baseUrl + "/api/file/video",
      fieldName: "file",
      headers: {
        Authorization: "Bearer " + token,
      },
      customInsert(res, insertFn) {
        // res 即服务端的返回结果
        if (res.status === 200) {
          // 插入视频到编辑器
          insertFn(res.data.url, res.data.poster);
        } else {
          console.error("上传视频失败", res);
        }
      },
    },
  },
}));
const content = defineModel();
const mode = ref("default");
const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<style lang="scss" scoped>
.editor-container {
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>
